import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { View, Text } from '@ray-js/ray';
import dayjs from 'dayjs';

import { BottomSheet, DateTimePicker, Icon, Picker } from '@ray-js/smart-ui';
import Icons from '@/icons';

import Strings from '@/i18n';
import globalPopup, { PopupView } from '@/components/popup';
import Weeks from '../weeks';

import styles from './index.module.less';
import { BottomButton } from '../BottomButton';

const Config = {
  themeColor: '#4a99bc',
};
const cx = (val: number) => `${val}rpx`;

interface ILoopModeProps {
  loopMode: number;
  spaceDay: number;
  startDay: any;
  loops: string;
  handleValueChange: (key: string, value: any) => void;
  needSpaceMode: boolean;
  singleLoop: boolean;
}

export default class LoopMode extends Component<
  ILoopModeProps,
  { showBottomPopup: boolean; bottomType: 'few_days' | 'date' }
> {
  static defaultProps = {
    spaceDay: 1,
    startDay: new Date(),
    needSpaceMode: true,
    singleLoop: false,
  };

  constructor(props: ILoopModeProps) {
    super(props);
    console.log(`🚀 ~ props:`, props);

    this.state = {
      showBottomPopup: false,
      bottomType: 'date',
    };

    this.spaceDay = 1;
    this.startDay = new Date(props.startDay);
  }

  handlerSelectMode = (mode: number) => {
    const { loopMode, spaceDay } = this.props;
    if (loopMode === mode && mode === 3) {
      this.toggleBottomSheet('few_days');
    } else {
      console.log({ mode });
      this.props.handleValueChange('loopMode', mode);
    }
  };

  handlerSelectDate = () => {
    this.toggleBottomSheet('date');
  };

  renderWeekList = () => {
    return (
      <View style={{ paddingLeft: cx(24), paddingRight: cx(8) }}>
        <Weeks
          weeks={this.props.loops.split('').map(Number)}
          onChange={weeks => this.props.handleValueChange('loops', weeks.join(''))}
        />
      </View>
    );
  };

  toggleBottomSheet = (type?: 'few_days' | 'date') => {
    const { showBottomPopup } = this.state;
    this.setState({
      showBottomPopup: !showBottomPopup,
      bottomType: type || 'few_days',
    });
  };

  render() {
    const { loopMode, spaceDay, startDay, needSpaceMode, singleLoop } = this.props;
    const isToday = dayjs(new Date()).format('YYYYMMDD') === dayjs(startDay).format('YYYYMMDD');
    const data = [
      {
        title: Strings.getLang('weekly_cycle'),
        show: true,
      },
      {
        title: Strings.getLang('odd_day'),
        subTitle: Strings.getLang('odd_subtitle'),
        show: !singleLoop,
      },
      {
        title: Strings.getLang('even_day'),
        subTitle: Strings.getLang('even_subtitle'),
        show: !singleLoop,
      },
      {
        title: Strings.getLang('few_days'),
        show: !singleLoop && needSpaceMode,
      },
    ];

    const { showBottomPopup, bottomType } = this.state;
    return (
      <>
        {data.map((item, index) => {
          return (
            item.show && (
              <View className={styles.loopWrap} key={index}>
                <View className={styles.loopRow} onClick={() => this.handlerSelectMode(index)}>
                  <Icon
                    name={loopMode === index ? Icons.selected : Icons.unselected}
                    size={18}
                    color={loopMode === index ? Config.themeColor : '#E5E5E5'}
                  />
                  <View style={{ flex: 1, paddingLeft: cx(8) }}>
                    <View className={needSpaceMode && styles.modeRow}>
                      <Text
                        style={{
                          fontSize: '32rpx',
                          color: '#333',
                        }}
                      >
                        {item.title}
                      </Text>
                      {loopMode === 3 && index === 3 && (
                        <View
                          style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}
                        >
                          <Text>{Strings.formatValue('every_few_days', spaceDay)}</Text>
                          <Icon
                            name={Icons.arrow}
                            color="#999"
                            customStyle={{ marginLeft: cx(8) }}
                          />
                        </View>
                      )}
                    </View>
                    {item.subTitle && (
                      <Text style={{ marginTop: cx(4), fontSize: cx(24), color: '#999' }}>
                        {item.subTitle}
                      </Text>
                    )}
                  </View>
                </View>
                {loopMode === 0 && index === 0 && this.renderWeekList()}
                {loopMode === 3 && index === 3 && (
                  <View className={styles.startDateRow} onClick={() => this.handlerSelectDate()}>
                    <Text>{Strings.getLang('start_day')}</Text>
                    <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                      <Text>
                        {isToday ? Strings.getLang('today') : dayjs(startDay).format('YYYY/MM/DD')}
                      </Text>
                      <Icon name={Icons.arrow} color="#999" customStyle={{ marginLeft: cx(8) }} />
                    </View>
                  </View>
                )}
              </View>
            )
          );
        })}
        <PopupView />

        <BottomSheet
          show={showBottomPopup}
          title={Strings.getLang(bottomType === 'date' ? 'start_day' : 'space_day')}
          iconColor="transparent"
          // @ts-ignore
          onClose={this.toggleBottomSheet}
        >
          {bottomType === 'few_days' ? (
            <Picker
              columns={new Array(31).fill(0).map((_, i) => i + 1)}
              onChange={e => {
                this.spaceDay = e.detail.value;
              }}
            />
          ) : (
            <DateTimePicker
              type="date"
              minDate={new Date().getTime()}
              maxDate={dayjs().add(100, 'year').toDate().getTime()}
              locale={{
                year: '年',
              }}
              showToolbar={false}
              formatterMap={{
                month: '{{month}}月',
                day: '{{day}}日',
              }}
              onInput={e => {
                console.log('🚀 ~ e:', e);
                this.startDay = e.detail;
              }}
            />
          )}

          <BottomButton
            handleConfirm={() => {
              if (bottomType === 'few_days') {
                this.props.handleValueChange('spaceDay', this.spaceDay);
                this.spaceDay = 1;
              }

              if (bottomType === 'date') {
                this.props.handleValueChange('startDay', this.startDay);
                this.startDay = new Date(startDay);
              }

              this.toggleBottomSheet();
            }}
            handleCancel={() => {
              this.spaceDay = 1;

              this.startDay = new Date(startDay);

              this.toggleBottomSheet();
            }}
          />
        </BottomSheet>
      </>
    );
  }
}
